package com.yangcangclub.commons.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自动生成bean，仅供开发时使用，<br>
 * 严禁在测试和生产环境的业务代码里上使用，否则后果自负
 */
public class TableToBeanUtil {

    static String sql = null;
    static DBHelper db1 = null;
    static ResultSet rs = null;

    public static void main(String[] args) throws Exception {

        ConvetToBean("yc_shopping_trolley");

    }

    //获取字段注释
    public static Map getTableComment(String table) throws Exception {
        Map rmap=new HashMap();
        Connection conn= new DBHelper().getConn();
        ResultSet resultSet= conn.getMetaData().getTables(null,"%",table,new String[]{"TABLE"});

        while (resultSet.next()) {
            String tableName=resultSet.getString("TABLE_NAME");
            if(tableName.equals(table)){
                ResultSet rs = conn.getMetaData().getColumns(null, null,tableName, "%");
                while(rs.next()){
                    String colName = rs.getString("COLUMN_NAME");
                    String remarks = rs.getString("REMARKS");
                    if(remarks == null || remarks.equals("")){
                        remarks = colName;
                    }
                    rmap.put(colName,remarks);
                }
            }
        }
        return rmap;
    }

    //table to  bean 
    public static void ConvetToBean(String tableName){
        sql = "select * from " +tableName;//SQL语句
        db1 = new DBHelper(sql);//创建DBHelper对象
        try {
            rs = db1.pst.executeQuery();//执行语句，得到结果集
            ResultSetMetaData rsmd=rs.getMetaData();//得到字段信息
            Map mm=getTableComment(tableName);//得到字段注释Map
            for(int i=1;i<rsmd.getColumnCount()+1;i++) {
                String ColumnName=rsmd.getColumnName(i);
                System.out.print(getColumnType(rsmd.getColumnClassName(i),ColumnName));
                System.out.println(" \t/** "+mm.get(ColumnName)+" */");
            }

            System.out.println("\n\t//region getters and setters");
            for(int i=1;i<rsmd.getColumnCount()+1;i++) {
                String ColumnName=rsmd.getColumnName(i);//数据库字段名
                String javaClassname=rsmd.getColumnClassName(i);//全限定类名
                System.out.println(getGettersandSetters(javaClassname,ColumnName));
            }
            System.out.println("\t//endregion");
            rs.close();
            db1.close();//关闭连接
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取bean的字段描述
    public static String getColumnType(String ColumnClassName,String ColumnName){
        ColumnClassName=ColumnClassName.substring(ColumnClassName.lastIndexOf(".")+1,ColumnClassName.length());
        ColumnName=ColumnName.toLowerCase();

        ColumnName=NamePase(ColumnName);//格式转换
        if(ColumnClassName.equals("Integer")) return "private int "+ColumnName+";";
        if(ColumnClassName.equals("Long")) return "private long "+ColumnName+";";
        if(ColumnClassName.equals("Double")) return "private double "+ColumnName+";";
        if(ColumnClassName.equals("Float")) return "private float "+ColumnName+";";
        if(ColumnClassName.equals("Character")) return "private char " +ColumnName+";";
        if(ColumnClassName.equals("Boolean")) return "private boolean "+ColumnName+";";
        if(ColumnClassName.equals("Byte")) return "private byte "+ColumnName+";";
        if(ColumnClassName.equals("Short")) return "private short "+ColumnName+";";
        if(ColumnClassName.equals("String")) return "private String "+ColumnName+";";
        if(ColumnClassName.equals("BigDecimal")) return "private BigDecimal "+ColumnName+";";
        if(ColumnClassName.equals("Timestamp")) return "private Date "+ColumnName+";";
        return "private Object "+ColumnName+";";
    }

    //ColumnName-数据库字段名；ColumnClassName--java全限定类名
    public static String getGettersandSetters(String ColumnClassName,String ColumnName){
        ColumnClassName= ColumnClassName.substring(ColumnClassName.lastIndexOf(".")+1,ColumnClassName.length());
        ColumnName=ColumnName.toLowerCase();
        String fieldName=NamePase(ColumnName);//格式转换
        char[] cs=fieldName.toCharArray();
        cs[0]-=32;
        String FieldName= String.valueOf(cs);//变成首字母大写
        String simpleType="";
        //类型转换
        if(ColumnClassName.equals("Integer")) simpleType="int";
        else if(ColumnClassName.equals("Long")) simpleType="long";
        else if(ColumnClassName.equals("Double")) simpleType="double";
        else if(ColumnClassName.equals("Float")) simpleType="float";
        else if(ColumnClassName.equals("Character")) simpleType="char";
        else if(ColumnClassName.equals("Boolean")) simpleType="boolean";
        else if(ColumnClassName.equals("Byte")) simpleType="byte";
        else if(ColumnClassName.equals("Short")) simpleType="short";
        else if(ColumnClassName.equals("String")) simpleType="String";
        else if(ColumnClassName.equals("BigDecimal")) simpleType="BigDecimal";
        else if(ColumnClassName.equals("Timestamp")) simpleType="Date";
        else simpleType="Object";

        StringBuffer sb=new StringBuffer("public ").append(simpleType)
                .append(" get" ).append(FieldName)
                .append("() {").append("return ").append(fieldName).append(";}\n")
                .append("public void set").append(FieldName).append("(").append(simpleType)
                .append(" ").append(fieldName).append(") {this.").append(fieldName).append(" = ")
                .append(fieldName).append(";}");
        return sb.toString();
    }

    /**将下划线分割的列名转换为驼峰
     * create_time to createTime
     * @return
     */
    public static String NamePase(String columnName){
        StringBuffer sb=new StringBuffer(columnName);
        while(sb.indexOf("_")!=-1&&sb.indexOf("_")<sb.length()-1){
            sb.replace(sb.indexOf("_"),sb.indexOf("_")+2, sb.substring(sb.indexOf("_")+1, sb.indexOf("_")+2).toUpperCase());
        }
        return sb.toString();
    }


}
